package com.example.xianji.activity;

import java.io.ByteArrayOutputStream;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.xianji.Contant;
import com.example.xianji.R;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.example.xianji.widgets.CustomProgressDialog;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Main_Up_Load_ZiZhiActivity extends Activity implements OnClickListener {
    public static int up_load;
    private Button submit_zizhi;
    private ImageView up_load_image;
    private LinearLayout layout;
    private ListView show_listview;
    private PopupWindow show_popupWindow;
    private String group[] = new String[]{"手机相册", "拍照", "取消"};
    private String photoStr;
    //    private SharedPreferences sp;
//    private Editor ed;
    private EditText edittext_title;
    private CustomProgressDialog mCustomProgressDialog;
    private ImageView up_load_zizhi_back;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
            }
        }
    };

    /**
     * 二进制转字符串
     *
     * @param b
     * @return
     */
    public static String byte2hex(byte[] b) {
        StringBuffer sb = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                sb.append("0" + stmp);
            } else {
                sb.append(stmp);
            }
        }
        return sb.toString();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main__up__load__zi_zhi);

        submit_zizhi = (Button) findViewById(R.id.submit_zizhi);
        up_load_image = (ImageView) findViewById(R.id.up_load_image);
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        edittext_title = (EditText) findViewById(R.id.edittext_title);
        up_load_zizhi_back = (ImageView) findViewById(R.id.up_load_zizhi_back);
        submit_zizhi.setOnClickListener(this);

        up_load_image.setOnClickListener(this);
        up_load_zizhi_back.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.submit_zizhi) {
            mCustomProgressDialog = CustomProgressDialog.createDialog(this);
            mCustomProgressDialog.setCanceledOnTouchOutside(false);
            mCustomProgressDialog.show();
            sumbit_zizhi();
        } else if (v.getId() == R.id.up_load_image) {
            Photo_show();
            show_popupWindow.showAtLocation(findViewById(R.id.up_load_zizhi_linear), Gravity.BOTTOM, 0, 0);
            show_listview.setAdapter(new ArrayAdapter<String>(Main_Up_Load_ZiZhiActivity.this, R.layout.information_show_photo_item, R.id.show_photo_item_text, group));
            show_listview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    if (group[arg2].equals("手机相册")) {
                        show_popupWindow.dismiss();

                        /**
                         * 下面这句话，与其它方式写是一样的效果，如果：
                         * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                         * intent.setType(""image/*");设置数据类型
                         * 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
                         * 这个地方小马有个疑问，希望高手解答下：就是这个数据URI与类型为什么要分两种形式来写呀？有什么区别？
                         */
							/*intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
							startActivityForResult(intent, 1);*/
                        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, 1);
                    }
                    if (group[arg2].equals("拍照")) {
                        show_popupWindow.dismiss();
                        /**
                         * 下面这句还是老样子，调用快速拍照功能，至于为什么叫快速拍照，大家可以参考如下官方
                         * 文档，you_sdk_path/docs/guide/topics/media/camera.html
                         * 我刚看的时候因为太长就认真看，其实是错的，这个里面有用的太多了，所以大家不要认为
                         * 官方文档太长了就不看了，其实是错的，这个地方小马也错了，必须改正
                         */
							/*Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
									.fromFile(new File(Environment
											.getExternalStorageDirectory(),
											"xiaoma.jpg")));
				 			startActivityForResult(intent, 2);*/
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                        startActivityForResult(intent, 2);
                    }
                    if (group[arg2].equals("取消")) {
                        show_popupWindow.dismiss();
                    }
                }
            });
        } else if (v.getId() == R.id.up_load_zizhi_back) {
            this.finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case 1:
                    Uri selectedImage = data.getData();
                    String[] filePathColumns = {MediaStore.Images.Media.DATA};
                    Cursor c = this.getContentResolver().query(
                            selectedImage, filePathColumns, null, null, null);
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePathColumns[0]);
                    String picturePath = c.getString(columnIndex);// 取出图片路径
                    c.close();
                    Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
                    show(bitmap);
                    break;
                case 2:
                    Bitmap bitmap1 = (Bitmap) data.getExtras().get("data");
                    show(bitmap1);
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void show(Bitmap photo) {
        up_load_image.setImageBitmap(photo);

        /**
         * 转化成16进制
         */
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        photo.compress(Bitmap.CompressFormat.PNG, 100, stream);// (0 - 100)压缩文件
        byte[] bt = stream.toByteArray();
        photoStr = byte2hex(bt);
    }

    private void Photo_show() {
        layout = (LinearLayout) LayoutInflater.from(
                Main_Up_Load_ZiZhiActivity.this).inflate(
                R.layout.information_shoow_photo, null);
        show_listview = (ListView) layout.findViewById(R.id.information_photo_listview);
        show_listview.setCacheColorHint(0);
        show_popupWindow = new PopupWindow(layout, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        show_popupWindow.setBackgroundDrawable(new BitmapDrawable());
        show_popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        show_popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        show_popupWindow.update();
        show_popupWindow.setOutsideTouchable(true);
        show_popupWindow.setFocusable(true);
        show_popupWindow.setContentView(layout);
    }

    public void sumbit_zizhi() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("qualifica", photoStr);
        parms.addBodyParameter("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        parms.addBodyParameter("title", edittext_title.getText().toString());
        httpUtils.send(HttpMethod.POST, Contant.tijiao_zizhi, parms, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                handler.sendEmptyMessage(1);
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                JSONObject object;
                try {
                    object = new JSONObject(arg0.result);
                    Toast.makeText(Main_Up_Load_ZiZhiActivity.this, object.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (object.getInt("status") == 1) {
                        up_load = 1;
                        Main_Up_Load_ZiZhiActivity.this.finish();
                    }
                    handler.sendEmptyMessage(1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}